package com.qf.test;

import com.qf.utils.ESUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.junit.Test;

import java.io.IOException;

public class HighLightDemo {

    @Test
    public void highLight() throws IOException {
        //1. 创建指定的Request对象，并设置索引名称和doc_id
        SearchRequest request = new SearchRequest();
        request.indices("sms-logs-index");

        //2. 设置添加的数据给Request对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //2.1 查询条件
        sourceBuilder.query(QueryBuilders.matchQuery("smsContent","北京"));

        //2.2 高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.fragmentSize(50);
        highlightBuilder.preTags("<span style='color:red;'>");
        highlightBuilder.postTags("</span>");
        highlightBuilder.field("smsContent");
        sourceBuilder.highlighter(highlightBuilder);

        //2.3 sourceBuilder封装到Request
        request.source(sourceBuilder);

        //3. 通过连接对象将Request发送给ES，并接受Response
        SearchResponse resp = ESUtil.getClient().search(request, RequestOptions.DEFAULT);

        //4. 通过Response判断添加是否成功
        for (SearchHit hit : resp.getHits().getHits()) {
            HighlightField highlightField = hit.getHighlightFields().get("smsContent");
            Text[] text = highlightField.getFragments();
            System.out.println(text[0]);
        }
    }
}
